<?php
/**
 *
 */
abstract class Cola_Controller
{
    /**
     * Template file extension
     *
     * @var string
     */
    public $tplExt = '.php';

    /**
     * Constructor
     *
     */
    public function __construct() {}

    /**
     * Magic method
     *
     * @param string $methodName
     * @param array $args
     */
    public function __call($method, $args)
    {
        throw new Cola_Exception("Call to undefined method: Cola_Controller::{$method}()");
    }

    /**
    * Get var
    *
    * @param string $key
    * @param mixed $default
    */
    protected function get($key = null, $default = null)
    {
        return Cola_Request::get($key, $default);
    }

    /**
    * Post var
    *
    * @param string $key
    * @param mixed $default
    */
    protected function post($key = null, $default = null)
    {
        return Cola_Request::post($key, $default);
    }

    /**
    * Param var
    *
    * @param string $key
    * @param mixed $default
    */
    protected function param($key = null, $default = null)
    {
        return Cola_Request::param($key, $default);
    }

    /**
     * View
     *
     * @param array $config
     * @return Cola_View
     */
    protected function view($viewsHome = null)
    {
        return $this->view = new Cola_View($viewsHome);
    }
    
    /**
     * template
     *
     * @param array $config
     * @return Cola_Template
     */
    protected function template($viewsHome = null)
    {
        return $this->template = new Cola_Template($viewsHome);
    }        

    /**
     * Display the view
     *
     * @param string $tpl
     */
    protected function display($tpl = null, $dir = null)
    {
        if (empty($tpl)) {
            $tpl = $this->defaultTemplate();
        }
        $this->view->display($tpl, $dir);
    }
    
    /**
     * Display the view
     *
     * @param string $tpl
     */
    protected function displayExt($parentTpl = '',$tpl = null)
    {
        if (empty($tpl)) {
            $dispatchInfo = Cola::getInstance()->dispatchInfo;
            $tpl = $dispatchInfo['module'].DIRECTORY_SEPARATOR.$dispatchInfo['controller'].DIRECTORY_SEPARATOR.$dispatchInfo['action'];
        }

        $this->template->display($parentTpl,$tpl);
    } 

    /**
     * Get default template file path
     *
     * @return string
     */
    protected function defaultTemplate()
    {
        $dispatchInfo = Cola::getInstance()->dispatchInfo;

        $tpl = str_replace('_', DIRECTORY_SEPARATOR, substr($dispatchInfo['controller'], 0, -10))
             . DIRECTORY_SEPARATOR
             . substr($dispatchInfo['action'], 0, -6)
             . $this->tplExt;

        return $tpl;
    }

    /**
     * Redirect to other url
     *
     * @param string $url
     */
    protected function redirect($url, $code = 302)
    {
        $this->response->redirect($url, $code);
    }

    /**
     * Abort
     *
     * @param mixed $data
     * @param string $var jsonp var name
     *
     */
    protected function abort($data, $var = null)
    {
        if (!is_string($data)) {
            $data = json_encode($data);
        }
        echo $var ? "var {$var}={$data};" : $data;
        exit();
    }
	
	/**
	 * is_ajax() (add by sasou)
	 * Controller中使用方法：$this->controller->is_ajax()
     * 
	 * @return
	 */
	public function isAjax()
	{
		if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) ==
			'xmlhttprequest'))
			return true;
		return false;
	}
	
	/**
	 *	控制器 AJAX脚本输出 (add by sasou)
	 *  Controller中使用方法：$this->ajaxReturn()
     * 
	 * 	@param  int     $status  0:错误信息|1:正确信息
	 * 	@param  string  $message  显示的信息
	 * 	@param  array   $data    传输的信息
	 * 	@param  array   $type    返回数据类型，json|xml|eval|jsonp
	 *  @return object
	 */
	public function ajaxReturn($status, $message = '', $data = array(), $type = 'html') {
		$return_data = array('status' => $status, 'message' => $message, 'data' => $data);
		$type = strtolower($type);
		if ($type == 'html') { 
			header('Content-type: text/html'); 
			exit(json_encode($return_data));
		} elseif ($type == 'json') {
			header("Content-type: application/json");
			exit(json_encode($return_data));
		} elseif ($type == 'xml') {
			header('Content-type: text/xml'); 
			$xml = '<?xml version="1.0" encoding="utf-8"?>';
			$xml .= '<return>';
				$xml .= '<status>' .$status. '</status>';
				$xml .= '<message>' .$message. '</message>';
				$xml .= '<data>' .serialize($data). '</data>';
			$xml .= '</return>';
		 	exit($xml);
		} elseif ($type == "jsonp"){
			$callback = $this->get_gp('callback');
            $json_data = json_encode($return_data);
		    if (is_string($callback) && isset($callback[0])) {
            	exit("{$callback}({$json_data});");
            } else {
                exit($json_data);
            }
		} elseif ($type == 'eval') {
			exit($return_data);
		} else {
		
		}	
	}

    /**
     * Dynamic set vars
     *
     * @param string $key
     * @param mixed $value
     */
    public function __set($key, $value = null)
    {
        $this->$key = $value;
    }

    /**
     * Dynamic get vars
     *
     * @param string $key
     */
    public function __get($key)
    {
        switch ($key) {
            case 'view':
                $this->view();
                return $this->view;
                
            case 'template':
                $this->template();
                return $this->template;
                
            case 'request':
                $this->request = new Cola_Request();
                return $this->request;

            case 'response':
                $this->response = new Cola_Response();
                return $this->response;

            case 'config':
                $this->config = Cola::getInstance()->config;
                return $this->config;

            default:
                throw new Cola_Exception('Undefined property: ' . get_class($this) . '::' . $key);
        }
    }
}
